package com.hyt.it.ogt.kq.service.bm.mq;

import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.it.ogt.kq.service.bm.model.entity.StudentProject;
import com.hyt.it.ogt.kq.service.bm.model.param.GroupRegistrationExamineeInfo;
import com.hyt.it.ogt.kq.service.bm.service.IStudentProjectService;
import com.hyt.it.ogt.kq.common.bm.utils.RedisUtil;
import com.hyt.it.ogt.kq.common.bm.utils.RemoteUtil;
import com.hyt.loginfo.model.ExamineeRegisterVO;
import com.hyt.loginfo.remote.PermissionLoginClient;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 集体报名创建账号数据消费者
 *
 * @author huangwu
 * @date 2022-09-05
 */
@Component
@Slf4j
public class GroupRegistrationDataConsumer {

    @Resource
	private PermissionLoginClient permissionLoginClient;
    
    @Resource
	IStudentProjectService studentProjectService;
    
    @Resource
    private GroupRegistrationDataProducer groupRegistrationDataProducer;
    
    @Resource
    private RedisUtil redisUtil;
    
    

    @RabbitListener(
    		bindings = {@QueueBinding(value = @Queue( value = "${mq.groupregistration.queue}", 
    		autoDelete = "false",durable = "true"), 
    		exchange = @Exchange( value = "${mq.direct}",
    		type = ExchangeTypes.DIRECT),
            key = {"${mq.groupregistration.route}"})},
            concurrency = "${mq.groupregistration.concurrency}")
    public void pushPjDataListener(String json, Message message, Channel channel) throws IOException {
        log.info("[集体报名][创建账号][MQ消费消息]消费集体报名创建账号数据:【{}】", json);
        GroupRegistrationExamineeInfo groupRegistrationExamineeInfo = FastJsonUtil.getJsonToBean(json, GroupRegistrationExamineeInfo.class);
        try {
        	ExamineeRegisterVO examineeRegisterVO = groupRegistrationExamineeInfo.getExamineeRegisterVO();
        	String studentId = groupRegistrationExamineeInfo.getStudentId();
        	if(null != examineeRegisterVO) {
        		ApiResponse<Object> api = permissionLoginClient.addCandidate(examineeRegisterVO);
        		if (RemoteUtil.isSuccess(api)) {
        			String regId =  (String) api.getData();
        			log.info("[集体报名][创建账号][MQ消费消息]消费集体报名创建账号数据regId:【{}】", regId);
        			// 获取报名考生信息
        			StudentProject studentProject = studentProjectService.getProjectStudentById(studentId);
        			log.info("[集体报名][创建账号][MQ消费消息]消费集体报名创建账号数据studentId:【{}】,studentProject:【{}】", studentId, FastJsonUtil.getBeanToJson(studentProject));
        			if(null != studentProject) {
        				studentProject.setRegId(regId);
        				Boolean result = studentProjectService.saveOrUpdate(studentProject);
        				log.info("[集体报名][创建账号][MQ消费消息]消费集体报名创建账号数据studentId:【{}】, saveResult:[{}]", studentId, result);
        				if(!result) {
        					sendRepeatMsg(groupRegistrationExamineeInfo);
        				}
        			}else {
        				log.info("[集体报名][创建账号][MQ消费消息]消费集体报名创建账号数据未查询到studentprojectinfo,studentId:【{}】, studentProject:【{}】", studentId, FastJsonUtil.getBeanToJson(studentProject));
        				// 对于失败的数据重新push一个消息
        				sendRepeatMsg(groupRegistrationExamineeInfo);
        			}
        		}else {
                	log.info("[集体报名][创建账号][MQ消费消息]消费集体报名创建账号数据失败 params:[{}], result:[{}]", FastJsonUtil.getBeanToJson(examineeRegisterVO), FastJsonUtil.getBeanToJson(api));
                	// 对于失败的数据重新push一个消息
                	sendRepeatMsg(groupRegistrationExamineeInfo);
        		}
        	}
        } catch (Exception e) {
        	// 需要有异常处理流程，目前交给mq重试
        	log.info("[集体报名][创建账号][MQ消费消息]消费集体报名创建账号数据error:[{}]", json, e);
        	// 对于失败的数据重新push一个消息
        	sendRepeatMsg(groupRegistrationExamineeInfo);
        } finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }



	private void sendRepeatMsg(GroupRegistrationExamineeInfo groupRegistrationExamineeInfo) {
		ExamineeRegisterVO examineeRegisterVO = groupRegistrationExamineeInfo.getExamineeRegisterVO();
		Integer count = Integer.valueOf(0);
		if(null != redisUtil.get(examineeRegisterVO.getContent())) {
			count = Integer.valueOf(String.valueOf(redisUtil.get(examineeRegisterVO.getContent())));
		}
		if( count <= 3) {
			// 对于失败的数据重新push一个消息
        	groupRegistrationDataProducer.sendMessage(groupRegistrationExamineeInfo);
        	Integer count2 = Integer.valueOf(1);
    		if(null != redisUtil.get(examineeRegisterVO.getContent())) {
    			count2 = Integer.valueOf(String.valueOf(redisUtil.get(examineeRegisterVO.getContent())));
    			count2 += 1;
    		}
        	redisUtil.set(examineeRegisterVO.getContent(), count2, 60 * 30L);
		}
		
	}
}
